<!-- 组织-职位管理-标准职位体系管理页面 -->
<template>
  <a-modal
    width="50%"
    :visible="props.visible"
    title-align="center"
    @cancel="handleCancel"
    @ok="handleBeforeOk"
  >
    <template #title>
      <span>{{ props.oldData?.id ? '编辑职位层级' : '新增职位层级' }}</span>
    </template>
    <a-form ref="refForm" :model="form" :rules="rules" auto-label-width>
      <a-form-item field="name" label="职位层级" required show-colon>
        <a-input style="width: 350px" v-model="form.name" />
      </a-form-item>
      <a-form-item field="range" label="职级范围" show-colon>
        <template #label>
          <span>职级范围</span>
          <a-tooltip
            content="数字越大，表示职级的级别越高。最多只能选择两个数字，如选中两个数字例如选择6、23，则表示这个职等的职级范围是在6~23这个范围里面"
          >
            <icon-exclamation-circle-fill style="color: #165dff" />
          </a-tooltip>
        </template>

        <a-scrollbar style="height: 200px; overflow: auto">
          <div style="height: 300px; width: 350px">
            <a-checkbox-group
              :max="2"
              v-model="form.range"
              @change="checkMethod"
            >
              <template v-for="item in arr" :key="item">
                <a-checkbox
                  :value="item"
                  :disabled="disabledRange.includes(item)"
                >
                  <template #checkbox="{ checked, disabled }">
                    <div
                      :class="{
                        'custom-checkbox-card-checked': checked,
                        'custom-checkbox-card-disabled': disabled
                      }"
                      class="custom-checkbox-card"
                    >
                      {{ item }}
                    </div>
                  </template>
                </a-checkbox>
              </template>
            </a-checkbox-group>
          </div>
        </a-scrollbar>
      </a-form-item>
      <a-form-item label="描述" show-colon>
        <a-textarea
          v-model="form.remark"
          allow-clear
          style="width: 400px"
          :auto-size="{
            minRows: 8,
            maxRows: 8
          }"
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button
        type="primary"
        @click="handleBeforeOk"
        :loading="store.isLoading"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import {
  addPositionHierarchyList,
  setPositionHierarchyList,
  CheckPositionHierarchyList,
  getPositionHierarchyList
} from '@/apis/management/organization/baseSetting/PositionSystem/index';
import { validateRules } from '@/utils/common';
import { cloneDeep } from 'lodash';
import useGlobalParametersStore from '@/store/modules/globalParameters';

const store = useGlobalParametersStore();
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    oldData: any;

    list?: any; // 传进来的数据
  }>(),
  {
    visible: false
  }
);

const emit = defineEmits(['changeVisible', 'openRefresh']);
watch(
  () => props.visible,
  async () => {
    if (props.visible) {
      if (props.oldData) {
        form.name = cloneDeep(props.oldData.name);
        form.remark = props.oldData.remark;
        form.id = props.oldData.id;
        form.levelUp = props.oldData.levelUp;
        form.levelDown = props.oldData.levelDown;
        // form.range = [props.oldData.levelDown, props.oldData.levelUp];
      }
      getData();
    } else {
      form.name = '';
      form.remark = '';
      form.id = 0;
      form.levelUp = 0;
      form.levelDown = 0;
      form.range = [];
    }
  }
);
const refForm = ref<any>(null);
// 校验名字查重
const validateName = async (val: string, cb: any) => {
  try {
    if (val === props.oldData?.name && form.id) {
      //
      console.log(val, form);
    } else {
      const data = {
        name: val
      };
      const res = await validateRules(CheckPositionHierarchyList, data);
      if (res.code) {
        cb(`${res.msg}`);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = {
  name: [
    {
      required: true,
      trigger: "['change']",
      message: '请填写类型名称'
    },
    {
      validator: validateName
    }
  ],
  range: [
    {
      required: true,
      message: '请选择职级范围'
    }
  ]
};

let disabledRange: any = ref([]);
const getData = async () => {
  try {
    disabledRange.value = [];
    // let temp: any = new Set();
    let temp: any = [];
    const { content } = await getPositionHierarchyList({
      pageNumber: 0,
      pageSize: -1
    });
    content.forEach((item: any) => {
      if (item.id !== form?.id) temp.push([item.levelDown, item.levelUp]);
      else form.range = [item.levelDown, item.levelUp];
    });

    temp.forEach((item: any) => {
      let i = item[0];
      while (i <= item[1]) {
        disabledRange.value.push(i);
        i++;
      }
    });
    // temp = Array.from(temp).sort((a, b) => a - b);
    console.log(content);

    console.log(temp);
    console.log(disabledRange.value);
  } catch (error: unknown) {
    console.log(error);
  }
};
const handleCancel = () => {
  emit('changeVisible', false);
};
const handleBeforeOk = async () => {
  if (await refForm.value.validate()) return;
  if (props.oldData) {
    let { name, remark, id, levelUp, levelDown, range } = form;
    if (range.length > 1) {
      range.sort((a, b) => a - b);
      levelDown = range[0];
      levelUp = range[1];
    } else {
      levelDown = range[0];
      levelUp = range[0];
    }
    await setPositionHierarchyList({
      name,
      remark,
      id,
      levelUp,
      levelDown,
      createBy: +localStorage.getItem('userId')
    });
    emit('openRefresh', true);
  } else {
    let { name, remark, levelUp, levelDown, range } = form;
    if (range.length > 1) {
      range.sort((a, b) => a - b);
      levelDown = range[0];
      levelUp = range[1];
    } else {
      levelDown = range[0];
      levelUp = range[0];
    }

    await addPositionHierarchyList({
      name,
      remark,
      levelUp,
      levelDown,
      createBy: +localStorage.getItem('userId')
    });
    emit('openRefresh', true);
  }
  emit('changeVisible', false);
};
const form = reactive<any>({});

const arr = Array.from({ length: 100 }, (v, k) => k + 1);

const checkMethod = (val, e) => {
  console.log('====================================');
  console.log(val);
  console.log(e);
  console.log(form.range);
  console.log('====================================');
};
</script>

<style lang="less" scoped>
.checkItem {
  width: 50px;
  height: 50px;
  text-align: center;
  border: 1px solid #ccc;
  line-height: 50px;
}

.checkItem:active {
  color: red;
}
// .checkItem span {
//   position: relative;
//   transform: translateY(-50%);
// }

.custom-checkbox-card {
  // padding: 14px 18px;
  border: 1px solid var(--color-border-2);
  border-radius: 4px;
  width: 50px;
  height: 50px;
  box-sizing: border-box;
  text-align: center;
  line-height: 50px;
}

.custom-checkbox-card-disabled {
  // padding: 14px 18px;
  background-color: var(--color-border-2);
}

:deep(.arco-checkbox-group .arco-checkbox) {
  margin-right: 0;
}

.custom-checkbox-card-title {
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: bold;
  text-align: center;
}

.custom-checkbox-card:hover,
.custom-checkbox-card-checked,
.custom-checkbox-card:hover .custom-checkbox-card-mask,
.custom-checkbox-card-checked .custom-checkbox-card-mask {
  border-color: rgb(var(--primary-6));
}

.custom-checkbox-card-checked {
  background-color: var(--color-primary-light-1);
}

.custom-checkbox-card:hover .custom-checkbox-card-title,
.custom-checkbox-card-checked .custom-checkbox-card-title {
  color: rgb(var(--primary-6));
}

.custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
  background-color: rgb(var(--primary-6));
}
</style>
